//
//  YZMStockBuyViewController.m
//  YZMicroStock
//
//  Created by wangminhong on 16/3/25.
//  Copyright © 2016年 cqjr. All rights reserved.
//

#import "YZMStockBuyViewController.h"
#import "YZMStockUnitView.h"
#import "YZMRecommandView.h"
#import "YZMSegmentForChoose.h"
#import "YZMGridView.h"
#import "NSNumber+Utils.h"
#import "YZClient.h"
#import "YZMConfigureModel.h"
#import "YZMGridMoneyModel.h"
#import "YZMStockRealModel.h"
#import "YZMConfigureService.h"
#import "MBProgressHUD+Utils.h"
#import "YZMStockViewController.h"
#import "YZMAlertView.h"
#import "JSONBaseDeal.h"
#import "YZMWebViewService.h"
#import "NSError+YZM.h"
#import <DateTools/DateTools.h>
#import "Zhugeio/Zhuge.h"
#import "YZMTradeTypeDef.h"
#import "YZMSimulateViewController.h"
#import "YZMRedPacketInfor.h"
#import "YZMWarningHotView.h"
#import "YZMCaluateView.h"
#import "MTGuideImageView.h"
#import "YZMStockBuyModel.h"

@interface YZMStockBuyViewController()

@property (nonatomic, strong) UILabel *managementFeeLB;
@property (nonatomic, strong) UILabel *bondLB;
@property (nonatomic, strong) YZMGridView *gridView;
@property (nonatomic, strong) UILabel *stockNumberLB;
@property (nonatomic, strong) UILabel *stockTimeLB;
@property (nonatomic, strong) UILabel *stockUseLB;
@property (nonatomic, strong) UIButton *submitBT;
@property (nonatomic, strong) YZMConfigureModel *configureModel;
@property (nonatomic, strong) YZMStockRealModel *stock;
@property (nonatomic, strong) NSDate *stockFetchDate;


@property (nonatomic, assign) double buyMoney;
@property (nonatomic, strong) YZMConfigureModelForLever *lever;

@property (nonatomic, strong) NSString *quitLossMoney;
@property (nonatomic, strong) NSString *quitGainMoney;
@property (nonatomic, strong) NSString *principal;
@property (nonatomic, strong) NSString *serviceCharge;

@property (nonatomic, assign) NSInteger stockCount;
@property (nonatomic, assign) BOOL needReloadFlag;
@property (nonatomic, assign) double stockAmountStatistics;
@property (nonatomic, assign) double stockAmountHasUse;

@property (nonatomic, strong) YZMGridMoneyModel *gridMoneyModel;
@property (nonatomic, assign) YZM_TRADE_TYPE typeTrade;

@property (nonatomic, strong) UIView *redPacketView;
@property (nonatomic, strong) UILabel *redPacketLabel;
@property (nonatomic, strong) UIButton *expenseBtn;
@property (nonatomic, strong) UILabel *expenseLabel;
@property (nonatomic, strong) YZMRedPacketInfor *redPackModel;

@property (nonatomic, strong) YZMWarningHotView *hotView;

@property (nonatomic, strong) YZMCaluateView *caluateView;

@property (nonatomic, strong) YZMStockUnitView *balanceView;

@property (nonatomic, strong) NSMutableArray *arrPrincipal;// 保证金数组

@property (nonatomic, strong) YZMGridView *pricipalGridView;//保证金数量显示view

@property (nonatomic, strong) UIView *ivTotal;//总计view

@property (nonatomic, strong) UILabel *labelTotal;

@property (nonatomic, assign) BOOL isHaveRed;

@property (nonatomic, strong) YZMStockUnitView *bondView;

@property (nonatomic, strong) UIView *containerView;

@end

@implementation YZMStockBuyViewController

- (instancetype)init{
    
    self = [super init];
    if (self) {
        
        self.gridMoneyModel = self.configureModel.tradingMoneyList[0];
    }
    return self;
}

- (void)viewDidLoad{
    
    [super viewDidLoad];
    if (self.typeTrade==YZM_TRADE_TYPE_FOR_A_STOCK) {
        self.title=@"T+1点买A股";
        
        [self fetchActivityRedPacketInfor];
    }else if (self.typeTrade==YZM_TRADE_TYPE_FOR_A_STOCK_SIM){
        self.title = @"炒股大赛";
    }else if (self.typeTrade == YZM_TRADE_TYPE_FOR_A_STOCK_YLB){
        self.title = @"盈利宝";
    }
    
    self.view.backgroundColor = [YZMAppStyle appBackgroundColor];
    self.configureModel = [[YZMConfigureService sharedServiceWithTradeType:self.typeTrade].defaultConfigure copy];
    self.navigationItem.rightBarButtonItem = [YZMAppStyle rightBarItemWithTitle:@"规则" target:self action:@selector(rightBarItemPressed:)];
    
    [self createObjects];
    if (self.configureModel) {
        
        [self refreshView];
        [self refreshStockCanBuyTime:self.configureModel.maxCountOneDay - self.configureModel.buyCount];
    }
    [self fetchStockBuyConfigure];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.configureModel.signAgreement = [YZMConfigureService sharedServiceWithTradeType:self.typeTrade].defaultConfigure.signAgreement;

    //实名认证判断
    if (!YZMUserServiceInstance.user.detail.isNamed) {
        
        YZMAlertView *alertView = [YZMAlertView alertViewForRecommandWithContent:@"您还未实名认证，请先认证"];
        alertView.cancelButton.hidden = NO;
        [alertView.sureButton setTitle:@"立即验证" forState:UIControlStateNormal];
        alertView.confirmHandle = ^{
            
            [YZMHCMInstance pushViewControllerWithName:@"identifyVerify" andParams:nil];
            return YES;
        };
        alertView.cancleHandle = ^{
          
            [YZMHCMInstance popViewController:nil animated:YES];
        };
        [alertView showInView:self.navigationController.view];
        
        return;
    } else {
        if (self.typeTrade != YZM_TRADE_TYPE_FOR_A_STOCK_YLB) {
            NSUserDefaults* data = [NSUserDefaults standardUserDefaults];
            if (![data objectForKey:@"JIESUAN"]) {
                [MTGuideImageView createImage: (iPhoneX ? @"dma2" : (iPhone6P ? @"dma1" : @"dma3"))];
                [data setObject:@"1" forKey:@"JIESUAN"];
            }
        }
    }
    
    if (self.needReloadFlag) {
        
        [YZMConfigureService sharedServiceWithTradeType:self.typeTrade].defaultConfigure.balance = YZMUserServiceInstance.user.assets.balance;
        self.configureModel.balance = YZMUserServiceInstance.user.assets.balance;
        
        //获取价格
        [self requestToLoadReal];
    }
    
    self.needReloadFlag = YES;
}

#pragma mark -- network

- (void)requestToFetchStockAmountStatistics{
    
    [YZClient td_fetchStockAmonutStatisticsWithStockCode:self.stock.code success:^(NSURLResponse *response, id responseObject) {
        
        YZGeneralResultModel *topModel = responseObject;
        if (topModel.success) {
            
            self.stockAmountHasUse = [JSONBaseDeal getDoubleValue:@"money" fromData:topModel.data];
        }
        
    } failure:nil];
}

- (void)requestToFetchYLBStockAmountStatistics{
    [YZClient td_fetchYLBStockAmonutStatisticsWithStockCode:self.stock.code success:^(NSURLResponse *response, id responseObject) {
        
        YZGeneralResultModel *topModel = responseObject;
        if (topModel.success) {
            
            self.stockAmountHasUse = [JSONBaseDeal getDoubleValue:@"money" fromData:topModel.data];
        }
        
    } failure:nil];
}

-(void)requestStatisticsForSimulate{
    
    [YZClient simU_fetchStockAmonutStatisticsWithStockCode:self.stock.code success:^(NSURLResponse *response, id responseObject) {
        
        YZGeneralResultModel *topmodel=responseObject;
        if (topmodel.success) {
            
            self.stockAmountHasUse=[JSONBaseDeal getDoubleValue:@"money" fromData:topmodel.data];
        }
    } failure:nil];
}

- (void)requestToLoadReal{
    
    MBProgressHUD *hud = [MBProgressHUD showMessageManual:@"更新股票中"];
    
    __weak typeof(&*self) safeSelf = self;
    [YZClient qt_getRealtimeInfoWithStockCodes:@[self.stock.code] success:^(NSURLResponse *response, id responseObject) {
        
        YZGeneralResultModel *topModel = responseObject;
        if (topModel.success) {
            [hud hide:YES];
            NSDictionary *dict = topModel.data;
            safeSelf.stock = dict[self.stock.code];
            safeSelf.stockFetchDate = [NSDate date];
            [self refreshView];
            
        }else{
            
            [hud hide:NO];
            [topModel showMessage];
        }
        
    } failure:^(NSError *error) {
        
        [hud hide:NO];
        [error yz_showMessage];
    }];
}

- (void)fetchStockBuyConfigure{
    
    MBProgressHUD *hud = [MBProgressHUD showMessageManual:@"更新配置参数中"];
    
    __weak __typeof(&*self) weakSelf = self;
    [[YZMConfigureService sharedServiceWithTradeType:self.typeTrade] fetchConfigureDataSuccess:^{
        
        [hud hide:NO];
        YZMConfigureModel *defaultModel = [YZMConfigureService sharedServiceWithTradeType:self.typeTrade].defaultConfigure;
        YZMUserServiceInstance.user.assets.balance = defaultModel.balance;
        
        NSInteger canBuyTime = defaultModel.maxCountOneDay - defaultModel.buyCount;
        if (weakSelf.configureModel.maxCountOneDay - weakSelf.configureModel.buyCount!=  canBuyTime ) {
            
            [weakSelf refreshStockCanBuyTime:canBuyTime];
        }
        
        if (![defaultModel.version isEqualToString:weakSelf.configureModel.version]) {
            
            weakSelf.configureModel = [defaultModel copy];
            [weakSelf refreshView];
            
        }else{
            
            weakSelf.configureModel = [defaultModel copy];
        }
        weakSelf.stockAmountStatistics = weakSelf.configureModel.maxMoneyOneStock;
        if (self.typeTrade == YZM_TRADE_TYPE_FOR_A_STOCK) {
            [weakSelf requestToFetchStockAmountStatistics];
        }else if(self.typeTrade == YZM_TRADE_TYPE_FOR_A_STOCK_YLB){
            [weakSelf requestToFetchYLBStockAmountStatistics];
        }else{
            [weakSelf requestStatisticsForSimulate];
        }
        
    } failure:^(NSError *error) {
        
        [hud hide:NO];
        [error yz_showMessage];
    }];
}

- (void)submitStockBuyRequest{
    
    //判断是否超过一分钟时长
    if ([[NSDate date] timeIntervalSinceDate:self.stockFetchDate] >= 60) {
        
        YZMAlertView *alertView = [YZMAlertView alertViewForRecommandWithContent:@"超过一分钟，需重新获取股票价格后再重新发起"];
        alertView.confirmHandle = ^{
            
            [self requestToLoadReal];
            return YES;
        };
        
        return;
    }
    
    MBProgressHUD *hud = [MBProgressHUD showMessageManual:@"提交中"];
    if (self.typeTrade == YZM_TRADE_TYPE_FOR_A_STOCK_YLB) {
        [self requestTradeYLb:hud];
    }else{
        [YZClient td_submitTradeWithStockCode:self.stock.code andMoney:@(self.buyMoney).rfString andLever:self.lever.value andQuitGain:self.quitGainMoney andQuitLoss:self.quitLossMoney andPrincipal:self.principal andServiceCharge:self.serviceCharge andStockCount:self.stockCount andToken:self.configureModel.token andUseRedpack:self.expenseBtn.isSelected success:^(NSURLResponse *response, id responseObject) {
            
            [hud hide:NO];
            YZGeneralResultModel *topModel = responseObject;
            if (topModel.success) {
                
                [MBProgressHUD showMessage:@"点买成功"];
                
#ifndef DEBUG_MODE
                
                NSMutableDictionary *properties = [NSMutableDictionary dictionary];
                properties[@"名称"] = @"A股";
                [[Zhuge sharedInstance] track:@"交易" properties:properties];
#endif
                [YZMUserServiceInstance fetchUserAssetsInfo];
                UIViewController *viewController = [YZMHCMInstance instanceWithControllerName:@"stock"];
                if(viewController){
                    
                    YZMStockViewController *tradeVC = (YZMStockViewController *)viewController;
                    [[NSNotificationCenter defaultCenter] postNotificationName:PopScrollNSNOtification object:nil];
                    [tradeVC showSellListPage];
                }
                [YZMHCMInstance popViewController:nil animated:YES];
                
            }else{
                
                NSString *token = [topModel.data objectForKey:@"token"];
                if (token.length >0) {
                    
                    self.configureModel.token = token;
                }
                [[YZMAlertView alertViewForRecommandWithContent:topModel.resultMessage] showInView:self.navigationController.view];
            }
            
        } failure:^(NSError *error) {
            
            [hud hide:NO];
            [error yz_showMessage];
        }];
    }
}

- (void)requestTradeYLb:(MBProgressHUD *)hud{
    [YZClient td_submitTradeYLBWithStockCode:self.stock.code andMoney:@(self.buyMoney).rfString andLever:self.lever.value andQuitGain:self.quitGainMoney andQuitLoss:self.quitLossMoney andPrincipal:self.principal andServiceCharge:self.serviceCharge andStockCount:self.stockCount andToken:self.configureModel.token andUseRedpack:self.expenseBtn.isSelected success:^(NSURLResponse *response, id responseObject) {
        
        [hud hide:NO];
        YZGeneralResultModel *topModel = responseObject;
        if (topModel.success) {
            
            [MBProgressHUD showMessage:@"点买成功"];
            
#ifndef DEBUG_MODE
            
            NSMutableDictionary *properties = [NSMutableDictionary dictionary];
            properties[@"名称"] = @"A股";
            [[Zhuge sharedInstance] track:@"交易" properties:properties];
#endif
            [YZMUserServiceInstance fetchUserAssetsInfo];
            UIViewController *viewController = [YZMHCMInstance instanceWithControllerName:@"stockYLB"];
            if(viewController){
                
                YZMStockViewController *tradeVC = (YZMStockViewController *)viewController;
                [[NSNotificationCenter defaultCenter] postNotificationName:PopScrollNSNOtification object:nil];
                [tradeVC showSellListPage];
            }
            [YZMHCMInstance popViewController:nil animated:YES];
            
        }else{
            
            NSString *token = [topModel.data objectForKey:@"token"];
            if (token.length >0) {
                
                self.configureModel.token = token;
            }
            [[YZMAlertView alertViewForRecommandWithContent:topModel.resultMessage] showInView:self.navigationController.view];
        }
        
    } failure:^(NSError *error) {
        
        [hud hide:NO];
        [error yz_showMessage];
    }];
}

-(void)createStategry{
    //判断是否超过一分钟时长
    if ([[NSDate date] timeIntervalSinceDate:self.stockFetchDate] >= 60) {
        
        YZMAlertView *alertView = [YZMAlertView alertViewForRecommandWithContent:@"超过一分钟，需重新获取股票价格后再重新发起"];
        alertView.confirmHandle = ^{
            
            [self requestToLoadReal];
            return YES;
        };
        return;
    }
    
    MBProgressHUD *hud = [MBProgressHUD showMessageManual:@"提交中"];
    
    [YZClient simU_submitTradeWithStockCode:self.stock.code andMoney:@(self.buyMoney).rfString andLever:self.lever.value andQuitGain:self.quitGainMoney andQuitLoss:self.quitLossMoney andPrincipal:self.principal andServiceCharge:self.serviceCharge andStockCount:self.stockCount andToken:self.configureModel.token success:^(NSURLResponse *response, id responseObject) {
        
        [hud hide:NO];
        YZGeneralResultModel *topModel = responseObject;
        if (topModel.success) {
            
            [MBProgressHUD showMessage:@"点买成功"];
            
#ifndef DEBUG_MODE
            
            NSMutableDictionary *properties = [NSMutableDictionary dictionary];
            properties[@"名称"] = @"A股";
            [[Zhuge sharedInstance] track:@"交易" properties:properties];
#endif
            [YZMUserServiceInstance fetchUserAssetsInfo];
            UIViewController *viewController = [YZMHCMInstance instanceWithControllerName:@"Simulate"];
            if(viewController){
                
                YZMSimulateViewController *tradeVC = (YZMSimulateViewController *)viewController;
                [tradeVC showSellListPage];
            }
            [YZMHCMInstance popViewController:nil animated:YES];
            
        }else{
            
            NSString *token = [topModel.data objectForKey:@"token"];
            if (token.length >0) {
                
                self.configureModel.token = token;
            }
            [[YZMAlertView alertViewForRecommandWithContent:topModel.resultMessage] showInView:self.navigationController.view];
        }
        
    } failure:^(NSError *error) {
        
        [hud hide:NO];
        [error yz_showMessage];
    }];
}

- (void)clickToBuyStock:(UIButton *)sender{
    
    if (kNetworkNotReachability) {
        
        [NSError yz_showMessageForNoWifi];
        return;
    }
    
    //判断是否交易时段
    if (![[YZMConfigureService sharedServiceWithTradeType:self.typeTrade] isInTradeTimePeriods]) {
        
        [[YZMAlertView alertViewForRecommandWithContent:@"当前为非点买时段，无法发起策略"] showInView:YZMHCMInstance.currentNavationCtroller.view];
        return;
    }
    
    //判断单只股票交易金额限制
    double stockAmountCanBuy =  self.stockAmountStatistics - self.stockAmountHasUse;
    if ( [@(self.buyMoney) isGreaterThanDouble: stockAmountCanBuy]) {
        
        NSString *stockAmountCanBuyString = @(stockAmountCanBuy).p0fString;
        if (stockAmountCanBuy < 0) {
            stockAmountCanBuyString = @"0";
        }
        [[YZMAlertView alertViewForRecommandWithContent:[NSString stringWithFormat:@"个股持仓累计金额最多%@元，当前还可点买%@元",@(self.stockAmountStatistics).p0fString, stockAmountCanBuyString]] showInView:self.navigationController.view];
        return;
    }
    
    if (self.typeTrade == YZM_TRADE_TYPE_FOR_A_STOCK_YLB) {
        YZMConfigureService  *service = [YZMConfigureService sharedServiceWithTradeType:YZM_TRADE_TYPE_FOR_A_STOCK_YLB];
        if ([@(self.buyMoney) isGreaterThanDouble: service.defaultConfigure.totalSurplusMoney]) {
            YZMAlertView *alterView = [YZMAlertView alertViewForRecommandWithContent:[NSString stringWithFormat:@"当前盈利宝优惠操盘金剩余%@元，请修改点买金额或稍后重试",@(service.defaultConfigure.totalSurplusMoney).p0fString]];
            [alterView show];
            return;
        }
        
        if ([@(self.buyMoney) isGreaterThanDouble: service.defaultConfigure.userSurplusMoney]) {
            YZMAlertView *alterView = [YZMAlertView alertViewForRecommandWithContent:[NSString stringWithFormat:@"您的盈利宝点买金额剩余%@元，请修改点买金额或部分平仓后再试",@(service.defaultConfigure.userSurplusMoney).p0fString]];
            [alterView show];
            return;
        }
    }
    
    //判断是否超过一分钟时长
    if ([[NSDate date] timeIntervalSinceDate:self.stockFetchDate] >= 60) {
        
        YZMAlertView *alertView = [YZMAlertView alertViewForRecommandWithContent:@"超过一分钟，需重新获取股票价格后再重新发起"];
        alertView.confirmHandle = ^{
            
            [self requestToLoadReal];
            return YES;
        };
        [alertView showInView:self.navigationController.view];
        return;
    }
    
    //判断单只股票交易数量限制
    if (self.stockCount > [YZMConfigureService sharedServiceWithTradeType:self.typeTrade].defaultConfigure.maxStockCount) {
        
        [[YZMAlertView alertViewForRecommandWithContent:[NSString stringWithFormat:@"单股最高可购买数量为%@股",@([YZMConfigureService sharedServiceWithTradeType:self.typeTrade].defaultConfigure.maxStockCount)]] showInView:self.navigationController.view];
        return;
    }
    
    //判断余额是否足够
    double money = [self.serviceCharge doubleValue] + [self.principal doubleValue] + [YZMConfigureService sharedServiceWithTradeType:self.typeTrade].defaultConfigure.unHanldDeferCharge;
    if (self.typeTrade == YZM_TRADE_TYPE_FOR_A_STOCK) {
        
        if (self.expenseBtn.isSelected) {
            
            if ([@(self.redPackModel.tipBalance) isEqualGreaterThanDouble:[self.serviceCharge doubleValue]]) {
                
                money = [self.principal doubleValue] + [YZMConfigureService sharedServiceWithTradeType:self.typeTrade].defaultConfigure.unHanldDeferCharge;

            }else{
                
                money = [self.principal doubleValue] + [YZMConfigureService sharedServiceWithTradeType:self.typeTrade].defaultConfigure.unHanldDeferCharge + [self.serviceCharge doubleValue] - self.redPackModel.tipBalance;
            }
        }else{
            
            money = [self.serviceCharge doubleValue] + [self.principal doubleValue] + [YZMConfigureService sharedServiceWithTradeType:self.typeTrade].defaultConfigure.unHanldDeferCharge;
        }
    }
    
    double distanceMoney = [@([@(money).r2fString doubleValue] - [@([YZMConfigureService sharedServiceWithTradeType:self.typeTrade].defaultConfigure.balance).r2fString doubleValue]) doubleValue];;
    
    if (self.typeTrade == YZM_TRADE_TYPE_FOR_A_STOCK) {
        
        if ( [@(distanceMoney) isGreaterThanDouble:0.0] ) {
            //余额不足
            YZMAlertView *alertView = [[YZMAlertView alloc] initWithFrame:self.view.frame];
            alertView.contentLabel.textAlignment = NSTextAlignmentCenter;
            alertView.contentLabel.textColor = [YZMAppStyle colorForBlackText];
            alertView.contentLabel.font = [YZMAppStyle largeSizeBoldFont];
            alertView.confirmHandle = ^{
                [YZMHCMInstance pushViewControllerWithName:@"recharge" andParams:@{YZBACKFLAG:@(YES)}];
                return YES;
            };
            
            if ([@([YZMConfigureService sharedServiceWithTradeType:self.typeTrade].defaultConfigure.unHanldDeferCharge) isGreaterThanDouble:0.0] ) {
                alertView.contentLabel.text = [NSString stringWithFormat:@"账户历史策略未缴纳递延费共%@元,当前余额不足，无法买入，需充值%@元，是否立即充值？",@([YZMConfigureService sharedServiceWithTradeType:self.typeTrade].defaultConfigure.unHanldDeferCharge).r2fString, @(distanceMoney).r2fString];
            }else{
                
                alertView.contentLabel.text = [NSString stringWithFormat:@"账户余额不足，无法买入，需充值%@元，是否立即充值？",@(distanceMoney).r2fString];
            }
            [alertView showInView:self.navigationController.view];
            return;
        }
    }else if (self.typeTrade == YZM_TRADE_TYPE_FOR_A_STOCK_YLB){
        if ([@(distanceMoney) isGreaterThanDouble:0.0] ) {
            YZMAlertView *alertView = [[YZMAlertView alloc] initWithFrame:self.view.frame];
            alertView.contentLabel.textAlignment = NSTextAlignmentCenter;
            alertView.contentLabel.textColor = [YZMAppStyle colorForBlackText];
            alertView.contentLabel.font = [YZMAppStyle largeSizeBoldFont];
            alertView.confirmHandle = ^{
                [YZMHCMInstance pushViewControllerWithName:@"recharge" andParams:@{YZBACKFLAG:@(YES)}];
                return YES;
            };
            if ([@([YZMConfigureService sharedServiceWithTradeType:self.typeTrade].defaultConfigure.unHanldDeferCharge) isGreaterThanDouble:0.0] ) {
                alertView.contentLabel.text = [NSString stringWithFormat:@"账户历史策略未缴纳递延费共%@元,当前余额不足，无法买入，需充值%@元，是否立即充值？",@([YZMConfigureService sharedServiceWithTradeType:self.typeTrade].defaultConfigure.unHanldDeferCharge).r2fString, @(distanceMoney).r2fString];
            }else{
                  alertView.contentLabel.text = [NSString stringWithFormat:@"账户余额不足，无法买入，需充值%@元，是否立即充值？",@(distanceMoney).r2fString];
            }
          
            [alertView showInView:self.navigationController.view];
            return;
        }
    }else{
        //余额不足
        if ([@(distanceMoney) isGreaterThanDouble:0.0] ) {
            [[YZMAlertView alertViewForRecommandWithContent:@"模拟资金余额不足，暂时无法交易"] showInView:self.navigationController.view];
            return;
        }
    }

    if (self.typeTrade==YZM_TRADE_TYPE_FOR_A_STOCK || self.typeTrade == YZM_TRADE_TYPE_FOR_A_STOCK_YLB) {
        //判断是否第一次购买
        if (self.typeTrade==YZM_TRADE_TYPE_FOR_A_STOCK) {
            if (!self.configureModel.signAgreement) {
                [YZMHCMInstance pushViewControllerWithName:@"YZMStockBuyCheckViewController" andParams:@{@"tradeType":@(self.typeTrade)}];
                return;
            }
        }
        
    //判断是否有递延费
    if ([@([YZMConfigureService sharedServiceWithTradeType:self.typeTrade].defaultConfigure.unHanldDeferCharge) isGreaterThanDouble:0.0]) {
            
        //余额不足
        YZMAlertView *alertView = [[YZMAlertView alloc] initWithFrame:self.view.frame];
        alertView.contentLabel.textAlignment = NSTextAlignmentCenter;
        alertView.contentLabel.textColor = [YZMAppStyle colorForBlackText];
        alertView.contentLabel.font = [YZMAppStyle largeSizeBoldFont];
        alertView.confirmHandle = ^{
                
            [self submitStockBuyRequest];
            return YES;
        };
        alertView.contentLabel.text = [NSString stringWithFormat:@"账户历史策略未缴纳递延费共%@元,需缴纳后才能发起新策略，确定支付吗？",@([YZMConfigureService sharedServiceWithTradeType:self.typeTrade].defaultConfigure.unHanldDeferCharge).r2fString];
            
        [alertView showInView:self.navigationController.view];
        return;
        }
    }

    if (self.typeTrade==YZM_TRADE_TYPE_FOR_A_STOCK || self.typeTrade == YZM_TRADE_TYPE_FOR_A_STOCK_YLB) {
        
        [self submitStockBuyRequest];
    }else if(self.typeTrade==YZM_TRADE_TYPE_FOR_A_STOCK_SIM){
        [self createStategry];
    }
}

#pragma mark -- event

- (void)rightBarItemPressed:(id)sender{
    
    [YZMWebViewService openTradeRule:self.typeTrade];
}

//持仓时间
- (void)clickToShowTimeRecommand{
    
    YZMRecommandView *view = [YZMRecommandView new];
    view.titleLabel.text = @"持仓时间";
    if (self.typeTrade == YZM_TRADE_TYPE_FOR_A_STOCK_YLB) {
        view.contentLabel.text = @"盈利宝持仓周期为两个交易日。到期不支持递延，点买人可以提前发起点卖结束交易。";
    }else{
         view.contentLabel.text = @"2～20个交易日，符合条件自动递延，递延费从账户余额扣除，若余额不足或不符合递延条件，策略将由投资人点卖清算，T+20当日必须结算。";
    }
    [view showInView:self.navigationController.view];
}

//触发止盈
- (void)clickToShowProfitRecommand{
    
    YZMRecommandView *view = [YZMRecommandView new];
    view.titleLabel.text = @"触发止盈";
    view.contentLabel.text = @"当合作交易品种的浮动盈亏达到特定数值时，由投资人即时卖出交易品种全部持有数量进行止盈。";
    [view showInView:self.navigationController.view];
}

//触发止损
- (void)clickToShowLossRecommand{
    
    YZMRecommandView *view = [YZMRecommandView new];
    view.titleLabel.text = @"触发止损";
    view.contentLabel.text = @"当合作交易品种的浮动盈亏达到特定数值时，由投资人即时卖出交易品种全部持有数量进行止损。";
    [view showInView:self.navigationController.view];
}

//交易综合费
- (void)clickToShowManagementFeeRecommand{
    
    YZMGridMoneyModel *girdModel = [YZMConfigureService sharedServiceWithTradeType:self.typeTrade].defaultConfigure.tradingMoneyList[0];

    double buyMoney = girdModel.money;
    
    YZMRecommandView *view = [YZMRecommandView new];
    view.titleLabel.text = @"交易综合费";
    if (self.typeTrade == YZM_TRADE_TYPE_FOR_A_STOCK_YLB) {
        view.contentLabel.text = @"交易综合费是由点买人每次发起新的策略时平台收取的服务费用，盈利宝不收取交易综合费。";
    }else{
        if ([YZMConfigureService sharedServiceWithTradeType:self.typeTrade].defaultConfigure) {
            
            view.contentLabel.text = [NSString stringWithFormat:@"交易综合费包含发起的交易费，第二天的递延费，每万元点买金的交易综合费为%@元，每万元点买金的递延费%@元/天。%@万元交易综合费为%@元，递延费为%@元/天。",@([YZMConfigureService sharedServiceWithTradeType:self.typeTrade].defaultConfigure.serviceCharge).p2fString,@([YZMConfigureService sharedServiceWithTradeType:self.typeTrade].defaultConfigure.deferCharge).p2fString,
                                      @(buyMoney/10000),@([YZMConfigureService sharedServiceWithTradeType:self.typeTrade].defaultConfigure.serviceChargeForLittleMoney*buyMoney/10000).r2fString,@([YZMConfigureService sharedServiceWithTradeType:self.typeTrade].defaultConfigure.deferChargeForLittleMoney*buyMoney/10000).r2fString];
        }else{
            
            view.contentLabel.text = @"交易综合费包含发起的交易费和第二天的递延费，每万元点买金的交易综合费为49元，每万元点买金的递延费19元/天。";
        }
    }
    
    [view showInView:self.navigationController.view];
}

//履约保证金
- (void)clickToShowBondRecommand{
    
    YZMRecommandView *view = [YZMRecommandView new];
    view.titleLabel.text = @"履约保证金";
    view.contentLabel.text = @"履约保证金为点买人委托平台冻结用于履行交易亏损赔付义务的保证金，结束时根据策略盈亏结算。保证金越低风险也越大，保证金越高抗风险也越高。";
    [view showInView:self.navigationController.view];
}

- (void)recharge {
     [YZMHCMInstance pushViewControllerWithName:@"recharge" andParams:nil];
}

#pragma mark -- refresh ui

- (void)refreshView{
    
    self.gridView.dataList = self.configureModel.tradingMoneyList;
    self.pricipalGridView.dataList = self.arrPrincipal;
}

- (void)refreshStockCanBuyTime:(NSInteger)canBuyTime{
    
    //刷新可购买次数
    self.stockTimeLB.text = [NSString stringWithFormat:@"%@",@(canBuyTime)];
    if (canBuyTime == 0) {
        
        self.submitBT.enabled = NO;
        [self.submitBT setTitle:@"今日点买次数已用完" forState:UIControlStateNormal];
        
    }else{
        
        self.submitBT.enabled = YES;
        [self.submitBT setTitle:@"提交" forState:UIControlStateNormal];
    }
}

#pragma mark -- ui

- (void)createObjects{
    
    __weak __typeof(&*self) weakSelf = self;
    
    UIView *bottomView = [UIView new];
    bottomView.backgroundColor = [YZMAppStyle appBackgroundColor];
    [weakSelf.view addSubview:bottomView];
    
    [bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(weakSelf.view).offset(1);
        make.bottom.equalTo(weakSelf.view).offset(0);
        make.left.equalTo(weakSelf.view).offset(-1);
    }];
    
    self.submitBT = [YZMAppStyle submitButton];
    self.submitBT.enabled = YES;
    [self.submitBT setTitle:@"提交" forState:UIControlStateNormal];
    [self.submitBT addTarget:self action:@selector(clickToBuyStock:) forControlEvents:UIControlEventTouchUpInside];
    [bottomView addSubview:self.submitBT];
    [self.submitBT mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.edges.equalTo(bottomView).insets(UIEdgeInsetsMake(12, 15, 12, 15));
    }];
    
    UIScrollView *sv = [UIScrollView new];
    [self.view addSubview:sv];
    sv.bounces = NO;
    [sv mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.equalTo(weakSelf.view);
        make.bottom.equalTo(bottomView.mas_top);
    }];
    
    self.containerView = [UIView new];
    [sv addSubview:self.containerView];
    [self.containerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.width.top.equalTo(sv);
        make.bottom.equalTo(sv).offset(-16);
    }];

    
    //账户余额
    if (self.typeTrade != YZM_TRADE_TYPE_FOR_A_STOCK_SIM) {
        UIButton* balanceBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        balanceBtn.titleLabel.font = [YZMAppStyle mediumSizeFont];
        [YZMSetBorderAndCornerRadius setView:balanceBtn borderWidth:1.5 borderColor:[YZMAppStyle buttonSelectedColor] cornerRadius:3];
        [balanceBtn setTitle:@"充值" forState:UIControlStateNormal];
       
        [balanceBtn addTarget:self action:@selector(recharge) forControlEvents:UIControlEventTouchUpInside];
        [balanceBtn setTitleColor:[YZMAppStyle buttonSelectedColor] forState:UIControlStateNormal];
        [self.containerView addSubview:balanceBtn];
        [balanceBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.height.mas_equalTo(24);
            make.width.mas_equalTo(60);
        }];
        
        _balanceView = [YZMStockUnitView new];
        
        NSString* str = [@"账户余额: " stringByAppendingString: @(YZMUserServiceInstance.user.assets.balance).decimalr02fString];
        NSMutableAttributedString *detailAttString = [[NSMutableAttributedString alloc]initWithString:str];
        [detailAttString addAttribute:NSForegroundColorAttributeName value:[YZMAppStyle colorForIconColor] range:NSMakeRange(5,str.length - 5)];
        _balanceView.titleAttString = detailAttString;
        _balanceView.rightView = balanceBtn;
        _balanceView.topLineType = YZMStockUnitLineTypeForAll;
        _balanceView.bottomLineType = YZMStockUnitLineTypeForMarginLeft;
        [self.containerView addSubview:_balanceView];
        [_balanceView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.left.right.equalTo(self.containerView);
        }];
    }
    //股票名称
    
    //    UILabel *nameLB = [YZMAppStyle labelWithLargeWhite];
    //    nameLB.text  = [NSString stringWithFormat:@"%@ %@",self.stock.name, self.stock.code];
    
    YZMStockUnitView *nameView = [YZMStockUnitView new];
//    nameView.title = @"股票名称";
    nameView.title = [NSString stringWithFormat:@"%@ %@",self.stock.name, self.stock.code];
//    nameView.rightView = nameLB;
    nameView.titleFont = [YZMAppStyle largeSizeFont];
    nameView.topLineType = YZMStockUnitLineTypeForAll;
    nameView.bottomLineType = YZMStockUnitLineTypeForMarginLeft;
    [self.containerView addSubview:nameView];
    [nameView mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.top.left.right.equalTo(self.containerView);
        if (self.typeTrade != YZM_TRADE_TYPE_FOR_A_STOCK_SIM) {
            make.top.equalTo(_balanceView.mas_bottom);
        } else {
            make.top.left.right.equalTo(self.containerView);
        }
        make.left.right.equalTo(self.containerView);
    }];
    
    UIView* couldbuyTimes = [self couldbuyTimes];
    [self.containerView addSubview:couldbuyTimes];
    [couldbuyTimes mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(nameView).offset(15);
        make.right.equalTo(nameView).offset(-15);
    }];
    
    
    //点买金额GridView
    UIView *gridMoneyView = [self getGridMoneyView];
    [self.containerView addSubview:gridMoneyView];
    [gridMoneyView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(nameView.mas_bottom);
        make.left.right.equalTo(self.containerView);
    }];
    
    //履约保证金view
    UIView *principalView = [self getPricipalView];
    [self.containerView addSubview:principalView];
    [principalView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(gridMoneyView.mas_bottom);
        make.left.right.equalTo(self.containerView);
    }];
    UIView *bottomStringView = [self getStockNumberAndTimeView];
    [self.containerView addSubview:bottomStringView];
    [bottomStringView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(gridMoneyView).offset(15);
        make.right.equalTo(gridMoneyView);
    }];
    
   
    //触发止盈
    YZMSegmentForChoose *profitChooseView = [YZMSegmentForChoose new];
    profitChooseView.clickAction = ^(NSInteger index, NSNumber *number){
      
        NSNumber *gainMoney = weakSelf.configureModel.quitGainRatioList[index];
        weakSelf.quitGainMoney = @([gainMoney doubleValue]*weakSelf.gridMoneyModel.money).rfString;
    };
    
    YZMStockUnitView *profitView = [YZMStockUnitView new];
    profitView.title = @"触发止盈";
    profitView.topLineType = YZMStockUnitLineTypeForMarginLeft;
    profitView.rightLargeView = profitChooseView;
//    profitView.bottomLineType = YZMStockUnitLineTypeForMarginLeft;
    profitView.bottomLineType = YZMStockUnitLineTypeForNone;
    profitView.explainAction = ^(){
        
        [weakSelf clickToShowProfitRecommand];
    };
    [self.containerView addSubview:profitView];
    [profitView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(principalView.mas_bottom);
        make.left.right.equalTo(self.containerView);
    }];
    
    //触发止损
    YZMSegmentForChoose *chooseView = [YZMSegmentForChoose new];
    chooseView.isloss = YES;
    chooseView.clickAction = ^(NSInteger index, NSNumber *number){
        
//        weakSelf.lever = weakSelf.configureModel.levers[index];
//        weakSelf.principal = @(weakSelf.gridMoneyModel.money/weakSelf.lever.value).rfString;
//        weakSelf.quitLossMoney = [@"-" stringByAppendingString:@([weakSelf.principal doubleValue]*weakSelf.lever.rate).rfString];
//
//        weakSelf.bondLB.text = weakSelf.principal;
    };
    
    YZMStockUnitView *lossView = [YZMStockUnitView new];
    lossView.title = @"触发止损";
    lossView.topLineType = YZMStockUnitLineTypeForNone;
    lossView.bottomLineType = YZMStockUnitLineTypeForNone;
    lossView.rightLargeView = chooseView;
    lossView.explainAction = ^(){
        
        [weakSelf clickToShowLossRecommand];
    };
    [self.containerView addSubview:lossView];
    [lossView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(profitView.mas_bottom).offset(-15); //内部高度被写死了，只能先用偏移的方法
        make.left.right.equalTo(self.containerView);
    }];
    
//    UILabel *timeLB = [YZMAppStyle labelWithLargeYellow];
    UILabel *timeLB = [YZMAppStyle labelWithLargeWhite];
    if (self.typeTrade == YZM_TRADE_TYPE_FOR_A_STOCK_YLB) {
        timeLB.text = @"2个交易日";
    }else{
        timeLB.text = @"T+1/D";
    }
    //持仓时间
    YZMStockUnitView *timeView = [YZMStockUnitView new];
    timeView.title = @"持仓时间";
    timeView.rightView = timeLB;
//    timeView.topLineType = YZMStockUnitLineTypeForMarginLeft;
//    timeView.bottomLineType = YZMStockUnitLineTypeForMarginLeft;
    timeView.topLineType = YZMStockUnitLineTypeForNone;
    timeView.bottomLineType = YZMStockUnitLineTypeForNone;
    timeView.explainAction = ^(){
        
        [weakSelf clickToShowTimeRecommand];
    };
    [self.containerView addSubview:timeView];
    [timeView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(lossView.mas_bottom).offset(-15);
        make.left.right.equalTo(self.containerView);
    }];

    
    UIView *splitView = [UIView new];
    splitView.backgroundColor = [YZMAppStyle colorForSplitLine];
    [self.containerView addSubview:splitView];
    [splitView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(timeView.mas_bottom).offset(-0.5);
        make.left.equalTo(self.containerView).offset(15);
        make.right.equalTo(self.containerView).offset(-15);
        make.height.mas_equalTo(0.5);
    }];
    
    
    
    //交易综合费
    self.managementFeeLB = [YZMAppStyle labelWithLargeYellow];
    UIView *ivManageFee = [UIView new];
    UILabel *labelFeeYuan = [[UILabel alloc] init];
    labelFeeYuan.text = @"元";
    labelFeeYuan.font = [YZMAppStyle mediumSizeFont];
    labelFeeYuan.textColor = [YZMAppStyle colorForWhite];
    [ivManageFee addSubview:labelFeeYuan];
    [labelFeeYuan mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(ivManageFee);
        make.top.equalTo(ivManageFee);
        make.bottom.equalTo(ivManageFee);
    }];
    [ivManageFee addSubview:self.managementFeeLB];
    [self.managementFeeLB mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(labelFeeYuan.mas_left);
        make.centerY.equalTo(labelFeeYuan);
    }];
    YZMStockUnitView *managementFeeView = [YZMStockUnitView new];
    managementFeeView.title = @"交易综合费";
    managementFeeView.rightView = ivManageFee;
    if (self.typeTrade==YZM_TRADE_TYPE_FOR_A_STOCK) {
        UIView *iv = [[UIView alloc] init];
        [iv addSubview:self.hotView];
        WS(ws);
        self.hotView.handle = ^{
            ws.caluateView.arrData = @[@{@"tradeDay":@"7",@"T+1":@"49+19*5=144",@"T+D":@"29+77=106",@"discount":@"38"},@{@"tradeDay":@"15",@"T+1":@"49+19*13=296",@"T+D":@"29+165=194",@"discount":@"102"},@{@"tradeDay":@"30",@"T+1":@"49+19*28=581",@"T+D":@"29+330=359",@"discount":@"222"}];
            ws.caluateView.handle = ^{
                [YZMCMInstance pushByCheckingAuthWithName:@"stockTD" andParams:nil];
            };
            [ws.caluateView show];
        };
        [self.hotView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(iv);
        }];
        managementFeeView.rightSecondView = iv;
    }
//    managementFeeView.bottomLineType = YZMStockUnitLineTypeForMarginLeft;
    managementFeeView.bottomLineType = YZMStockUnitLineTypeForNone;
    managementFeeView.explainAction = ^(){
        
        [weakSelf clickToShowManagementFeeRecommand];
    };
    [self.containerView addSubview:managementFeeView];
    [managementFeeView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(splitView.mas_bottom);
        make.left.right.equalTo(self.containerView);
    }];
    
    //履约保证金
    self.bondLB = [YZMAppStyle labelWithLargeYellow];
    UIView *ivBond = [UIView new];
    UILabel *labelbondYuan = [[UILabel alloc] init];
    labelbondYuan.text = @"元";
    labelbondYuan.font = [YZMAppStyle mediumSizeFont];
    labelbondYuan.textColor = [YZMAppStyle colorForWhite];
    [ivBond addSubview:labelbondYuan];
    [labelbondYuan mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(ivBond);
        make.top.equalTo(ivBond);
        make.bottom.equalTo(ivBond);
    }];
    [ivBond addSubview:self.bondLB];
    [self.bondLB mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(labelbondYuan.mas_left);
        make.centerY.equalTo(labelbondYuan);
    }];
    self.bondView = [YZMStockUnitView new];
    self.bondView.title = @"履约保证金";
    self.bondView.topLineType = YZMStockUnitLineTypeForNone;
    self.bondView.bottomLineType = YZMStockUnitLineTypeForNone;
    self.bondView.rightView = ivBond;
    self.bondView.explainAction = ^(){
        
        [weakSelf clickToShowBondRecommand];
    };
    [self.containerView addSubview:self.bondView];
    
    self.ivTotal = [[UIView alloc] init];
    self.ivTotal.backgroundColor = [YZMAppStyle colorForMain];
    UIView *ivLine = [[UIView alloc] init];
    ivLine.backgroundColor = [YZMAppStyle colorForSplitLine];
    [self.ivTotal addSubview:ivLine];
    [ivLine mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.ivTotal);
        make.height.mas_equalTo(0.5);
        make.left.equalTo(self.ivTotal).offset(15);
        make.right.equalTo(self.ivTotal).offset(-15);
    }];
    [self.containerView addSubview:self.ivTotal];
    if (self.typeTrade==YZM_TRADE_TYPE_FOR_A_STOCK) {
        [self.bondView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.equalTo(self.containerView);
            make.top.equalTo(managementFeeView.mas_bottom).offset(-10);
        }];
    }else if (self.typeTrade == YZM_TRADE_TYPE_FOR_A_STOCK_YLB){
        [self.bondView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.equalTo(self.containerView);
            make.top.equalTo(managementFeeView.mas_bottom).offset(-10);
        }];
       
        UIView *iv = [UIView new];
        iv.backgroundColor = [YZMAppStyle colorForMain];
        [self.containerView addSubview:iv];
        [iv mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.containerView);
            make.right.equalTo(self.containerView);
            make.top.equalTo(self.ivTotal.mas_bottom);
            make.height.mas_equalTo(30);
        }];
        UILabel *labelProtocol = [YZMAppStyle labelWithMediumWhite];
        labelProtocol.text = @"申请点买，即您已同意";
        [iv addSubview:labelProtocol];
        [labelProtocol mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(iv).offset(15);
            make.centerY.equalTo(iv);
        }];
        
        NSArray *contents = @[@"《平台投资人与点买人参与盈利宝合作协议》",@"《平台服务协议》"];
        UIView *delegateView = [UIView new];
        delegateView.backgroundColor = [YZMAppStyle colorForMain];
        [self.containerView addSubview:delegateView];
        [delegateView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.view);
            make.right.equalTo(self.view);
            make.top.equalTo(iv.mas_bottom);
            make.bottom.equalTo(self.containerView);
        }];
        
        UIView *lastView = nil;
        for (NSString *content in contents) {
            
            UIButton *subBT = [UIButton new];
//            subBT.backgroundColor = [UIColor redColor];
            subBT.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
            [subBT setTitle:content forState:UIControlStateNormal];
            [subBT setTitleColor:[YZMAppStyle colorForBlueText] forState:UIControlStateNormal];
            [subBT.titleLabel setNumberOfLines:0];
            subBT.tag = [contents indexOfObject:content];
            [subBT.titleLabel setFont:[YZMAppStyle smallSizeFont]];
            [subBT addTarget:self action:@selector(delegatePressed:) forControlEvents:UIControlEventTouchUpInside];
            [delegateView addSubview:subBT];
            [subBT mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.equalTo(delegateView).offset(12);
                make.right.equalTo(delegateView);
                if (lastView) {
                    make.top.equalTo(lastView.mas_bottom);
                }else{
                    make.top.equalTo(delegateView);
                }
            }];
            
            lastView = subBT;
        }
        
        [delegateView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.equalTo(lastView);
        }];
    }else if (self.typeTrade==YZM_TRADE_TYPE_FOR_A_STOCK_SIM){
        [self.bondView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.equalTo(self.containerView);
            make.top.equalTo(managementFeeView.mas_bottom).offset(-10);
//            make.bottom.equalTo(self.containerView);
        }];
    }
    
    //是否使用红包
    self.redPacketView = [UIView new];
    self.redPacketView.backgroundColor = [YZMAppStyle colorForMain];
    [self.containerView addSubview:self.redPacketView];
    self.redPacketView.hidden = YES;
    [self.redPacketView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.height.mas_equalTo(50);
        make.left.right.equalTo(self.containerView);
        make.top.equalTo(self.bondView.mas_bottom).offset(0); //33
//        make.bottom.equalTo(self.containerView);
    }];
    
    self.redPacketLabel = [YZMAppStyle labelWithSmallWhite];
    [self.redPacketView addSubview:self.redPacketLabel];
    self.redPacketLabel.text = @"是否使用红包余额（余额：158.00元）";
    [self.redPacketLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.equalTo(self.redPacketView).offset(13);
        make.top.equalTo(self.redPacketView).offset(5);
    }];
    
    UILabel *redPacketHintLB = [YZMAppStyle labelWithSmallLightGray];
    redPacketHintLB.text = @"红包余额只能抵扣交易综合费";
    [self.redPacketView addSubview:redPacketHintLB];
    [redPacketHintLB mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.equalTo(self.redPacketLabel.mas_bottom).offset(5);
        make.left.equalTo(self.redPacketLabel);
    }];
    
    self.expenseLabel = [YZMAppStyle labelWithSmallWhite];
    self.expenseLabel.text = @"-158元";
    [self.redPacketView addSubview:self.expenseLabel];
    [self.expenseLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.equalTo(self.redPacketLabel.mas_bottom);
        make.right.equalTo(self.redPacketView).offset(-15);;
    }];
    
    self.expenseBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.expenseBtn.selected = YES;
    [self.expenseBtn setImage:[UIImage imageNamed:@"icon_redpacket_unselected"] forState:UIControlStateNormal];
    [self.expenseBtn setImage:[UIImage imageNamed:@"icon_redpacket_selected"] forState:UIControlStateSelected];
    [self.expenseBtn addTarget:self action:@selector(selectedExpense:) forControlEvents:UIControlEventTouchUpInside];
    [self.redPacketView addSubview:self.expenseBtn];
    
    [self.expenseBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.height.width.mas_equalTo(12);
        make.centerY.equalTo(self.expenseLabel);
        make.right.equalTo(self.expenseLabel.mas_left).offset(-5);
    }];
    
   
    UILabel *labelYuan = [YZMAppStyle labelWithWhite];
    labelYuan.font = [YZMAppStyle mediumSizeFont];
    labelYuan.text = @"元";
    [self.ivTotal addSubview:labelYuan];
    [labelYuan mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.ivTotal);
        make.right.equalTo(self.ivTotal).offset(-15);
    }];
    self.labelTotal = [YZMAppStyle labelWithSmallYellow];
    self.labelTotal.font = [YZMAppStyle mediumSizeFont];
    self.labelTotal.text = @"";
    [self.ivTotal addSubview:self.labelTotal];
    [self.labelTotal mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.ivTotal);
        make.right.equalTo(labelYuan.mas_left).offset(-5);
    }];
    
    UILabel *labelInfo = [YZMAppStyle labelWithWhite];
    labelInfo.font = [YZMAppStyle mediumSizeFont];
    labelInfo.text = @"总计:";
    [self.ivTotal addSubview:labelInfo];
    [labelInfo mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.ivTotal);
        make.right.equalTo(self.labelTotal.mas_left).offset(-8);
    }];
    
    if (self.typeTrade == YZM_TRADE_TYPE_FOR_A_STOCK_SIM) {
        [self.ivTotal mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.equalTo(self.bondView);
            make.top.equalTo(self.bondView.mas_bottom);
            make.height.mas_equalTo(44);
            make.bottom.equalTo(self.containerView.mas_bottom).priorityMedium();
        }];
        self.labelTotal.text = @([self.principal doubleValue] + [self.serviceCharge doubleValue]).decimalr02fString;
    }else if (self.typeTrade == YZM_TRADE_TYPE_FOR_A_STOCK_YLB){
        [self.ivTotal mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.equalTo(self.bondView);
            make.top.equalTo(self.bondView.mas_bottom);
            make.height.mas_equalTo(44);
//            make.bottom.equalTo(self.containerView.mas_bottom).priorityMedium();
        }];
        self.labelTotal.text = @([self.principal doubleValue] + [self.serviceCharge doubleValue]).p0fString;
    }
    
    self.gridView.clickAction = ^(NSInteger index, YZMGridMoneyModel *data){
        
        weakSelf.gridMoneyModel = weakSelf.configureModel.tradingMoneyList[index];
        weakSelf.buyMoney = weakSelf.gridMoneyModel.money;
        weakSelf.stockCount = [@(weakSelf.gridMoneyModel.money/self.stock.price/self.configureModel.tradingCountRatio/100.0).rfString integerValue]*100;
        if (weakSelf.buyMoney >= 10000) {
        
            weakSelf.serviceCharge = @(weakSelf.gridMoneyModel.money/10000*self.configureModel.serviceCharge).r2fString;
        }else{
            
            weakSelf.serviceCharge = @(weakSelf.gridMoneyModel.money/10000*self.configureModel.serviceChargeForLittleMoney).r2fString;
        }
        //可买入股票数量
        weakSelf.stockNumberLB.text = [NSString stringWithFormat:@"%@",@(weakSelf.stockCount)];
        if (self.typeTrade == YZM_TRADE_TYPE_FOR_A_STOCK_YLB) {
            weakSelf.stockUseLB.text = [NSString stringWithFormat:@"%@%%",@(weakSelf.stockCount*weakSelf.stock.price / weakSelf.buyMoney*100).r2fString];
        }else{
            weakSelf.stockUseLB.text = @(weakSelf.stockCount*weakSelf.stock.price / weakSelf.buyMoney*100).r2fString;
        }
        
        
//        weakSelf.stockCount = [@(weakSelf.gridMoneyModel.money/self.stock.price/self.configureModel.tradingCountRatio/100.0).rfString integerValue]*100;

        weakSelf.managementFeeLB.text = weakSelf.serviceCharge;
        
        [weakSelf refreshExpenseLB];
        
//        NSMutableArray *leverArray = [NSMutableArray array];
        [weakSelf.arrPrincipal removeAllObjects];
        for (YZMConfigureModelForLever *lever in weakSelf.configureModel.levers) {
            YZMStockBuyModel *buyModel = [[YZMStockBuyModel alloc] init];
            buyModel.principal = @(weakSelf.gridMoneyModel.money/lever.value).rfString;
            buyModel.quainLoss = @([@(weakSelf.gridMoneyModel.money/lever.value).rfString doubleValue]*lever.rate).rfString;
            [weakSelf.arrPrincipal addObject:buyModel];
//            [leverArray addObject:[@"-" stringByAppendingString:@([@(weakSelf.gridMoneyModel.money/lever.value).rfString doubleValue]*lever.rate).rfString]];
        }
//        chooseView.itemList = leverArray;
        weakSelf.pricipalGridView.dataList = weakSelf.arrPrincipal;
        __strong __typeof__(weakSelf) strongSelf = weakSelf;
        strongSelf.pricipalGridView.clickAction = ^(NSInteger index, YZMStockBuyModel *data) {
            NSMutableArray *arr = [NSMutableArray array];
            [arr addObject:data.quainLoss];
            chooseView.itemList = arr;
            weakSelf.principal = data.principal;
            weakSelf.quitLossMoney = [NSString stringWithFormat:@"-%@",data.quainLoss];
            weakSelf.lever = weakSelf.configureModel.levers[index];
            weakSelf.bondLB.text = weakSelf.principal;
            if (weakSelf.expenseBtn.selected) {
                [weakSelf refreshExpenseLB];
            }else{
                weakSelf.labelTotal.text = @([weakSelf.principal doubleValue] + [weakSelf.serviceCharge doubleValue]).decimalr02fString;
            }
        };
        NSMutableArray *profitArray = [NSMutableArray array];
        for (NSNumber *number in weakSelf.configureModel.quitGainRatioList) {
            
            [profitArray addObject:@(weakSelf.gridMoneyModel.money*number.doubleValue).rfString];
        }
        profitChooseView.itemList = profitArray;
    };
}

#pragma mark - 协议
- (void)delegatePressed:(UIButton *)btn{
    switch (btn.tag) {
        case 0:
            [YZMWebViewService openFeeStandard:self.typeTrade];
            break;
        case 1:{
            [YZMWebViewService openRegisterAgreement];
        }
            break;
        default:
            break;
    }
}

#pragma mark netWorking
-(void)fetchActivityRedPacketInfor{
    
    //    WS(ws)
    [YZClient Activity_RedpacketInforsuccess:^(NSURLSessionDataTask *task, id responseObject) {
        YZGeneralResultModel *topModel = responseObject;
        if (topModel.success) {
            
            self.redPackModel = topModel.data;
            [self refreshRedPacker:self.redPackModel];
        }else{
            
            [topModel showMessage];
        }
    } failure:^(NSError *error) {
        
        [error yz_showMessage];
    }];
}

-(void)refreshRedPacker:(YZMRedPacketInfor *)infor{
    
    if ([@(infor.tipBalance) isGreaterThanDouble:0]) {
        
        self.redPacketView.hidden = NO;
        
        [self.ivTotal mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.redPacketView.mas_bottom);
            make.left.right.equalTo(self.redPacketView);
            make.height.mas_equalTo(44);
            make.bottom.equalTo(self.ivTotal.superview);
        }];
//        self.isHaveRed = YES;
//        self.expenseBtn.selected = YES;
    }else{
        [self.ivTotal mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.equalTo(self.bondView);
            make.top.equalTo(self.bondView.mas_bottom);
            make.height.mas_equalTo(44);
            make.bottom.equalTo(self.containerView.mas_bottom).priorityMedium();
        }];
    }
    [self refreshRedPacketInfo:infor];
}

//刷新红包信息
- (void)refreshRedPacketInfo:(YZMRedPacketInfor *)model {
    
    if (model) {
        
        self.redPacketLabel.text = [NSString stringWithFormat:@"是否使用红包余额（余额:%@元）", @(model.tipBalance).r2fString];
        [self refreshExpenseLB];
    }
}
- (void)refreshExpenseLB {
    
    if ([@(self.redPackModel.tipBalance) isEqualGreaterThanDouble:[self.managementFeeLB.text doubleValue]]) {
        
        self.expenseLabel.text = [@"-" stringByAppendingString:self.managementFeeLB.text];
        if (self.typeTrade == YZM_TRADE_TYPE_FOR_A_STOCK_YLB || self.typeTrade == YZM_TRADE_TYPE_FOR_A_STOCK_SIM) {
            self.labelTotal.text = @([self.principal doubleValue] + [self.serviceCharge doubleValue] - [self.managementFeeLB.text doubleValue]).decimalP0fString;
        } else {
            self.labelTotal.text = @([self.principal doubleValue] + [self.serviceCharge doubleValue] - [self.managementFeeLB.text doubleValue]).decimalr02fString;
        }
        
    } else {
        
        self.expenseLabel.text = [NSString stringWithFormat:@"-%@元", @(self.redPackModel.tipBalance).r2fString];
        if (self.typeTrade == YZM_TRADE_TYPE_FOR_A_STOCK_YLB || self.typeTrade == YZM_TRADE_TYPE_FOR_A_STOCK_SIM) {
            self.labelTotal.text = @([self.principal doubleValue] + [self.serviceCharge doubleValue] - self.redPackModel.tipBalance).decimalP0fString;
        } else {
            self.labelTotal.text = @([self.principal doubleValue] + [self.serviceCharge doubleValue] - self.redPackModel.tipBalance).decimalr02fString;
        }
        
    }
    
}

- (UIView *)getGridMoneyView{
    UIView *view = [UIView new];
    view.backgroundColor = [YZMAppStyle colorForMain];
    
    UILabel *titleLB = [YZMAppStyle labelWithMediumWhite];
    titleLB.text = @"点买金额";
    [view addSubview:titleLB];
    [titleLB mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.equalTo(view).offset(15);
    }];
    
    self.gridView = [YZMGridView new];
    [view addSubview:self.gridView];
    
    [self.gridView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(view).offset(15);
        make.top.equalTo(titleLB.mas_bottom).offset(15);
        make.right.equalTo(view).offset(-15);
        make.bottom.equalTo(view).offset(0);
    }];
    return view;
}

//履约保证金view
- (UIView *)getPricipalView{
    UIView *view = [UIView new];
    view.backgroundColor = [YZMAppStyle colorForMain];
    WS(weakSelf)
//
//    UILabel *titleLB = [YZMAppStyle labelWithMediumWhite];
//    titleLB.text = @"履约保证金";
//    [view addSubview:titleLB];
//    [titleLB mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.top.left.equalTo(view).offset(15);
//    }];
    
    YZMStockUnitView *PricipalView = [YZMStockUnitView new];
    PricipalView.title = @"履约保证金";
    PricipalView.topLineType = YZMStockUnitLineTypeForNone;
    PricipalView.bottomLineType = YZMStockUnitLineTypeForNone;
//    lossView.rightLargeView = chooseView;
    PricipalView.explainAction = ^(){
        [weakSelf clickToShowBondRecommand];
    };
    [view addSubview:PricipalView];
    
    [PricipalView mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.top.left.equalTo(view).offset(15);
        make.top.equalTo(view); //内部高度被写死了，只能先用偏移的方法
        make.left.right.equalTo(view);
    }];
    
    self.pricipalGridView = [YZMGridView new];
    self.pricipalGridView.type = YZMGridViewTypePrincipal;
    [view addSubview:self.pricipalGridView];
    
    [self.pricipalGridView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(view).offset(15);
        make.top.equalTo(PricipalView.mas_bottom);
        make.right.equalTo(view).offset(-15);
        make.bottom.equalTo(view).offset(-10);
    }];
    return view;
}

- (UIView *)getStockNumberAndTimeView{
    
    UIView *view = [UIView new];
    
    UILabel *label1 = [YZMAppStyle labelWithSmallWhite];
    label1.text = @"可买入";
    [view addSubview:label1];
    [label1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.bottom.equalTo(view);
    }];
    
    self.stockNumberLB = [YZMAppStyle labelWithSmallYellow];
    self.stockNumberLB.text = @"--";
    [view addSubview:self.stockNumberLB];
    [self.stockNumberLB mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(label1.mas_right);
        make.centerY.equalTo(label1);
    }];

    
    UILabel *label2 = [YZMAppStyle labelWithSmallWhite];
    label2.text = @"股，资金利用率";
    [view addSubview:label2];
    [label2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.stockNumberLB.mas_right);
        make.centerY.equalTo(label1);
    }];
    
    self.stockUseLB = [YZMAppStyle labelWithSmallYellow];
    self.stockUseLB.text = @"--";
    [view addSubview:self.stockUseLB];
    [self.stockUseLB mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.equalTo(label2.mas_right);
        make.centerY.equalTo(label1);
//        if (self.typeTrade == YZM_TRADE_TYPE_FOR_A_STOCK_YLB) {
//            make.right.equalTo(view);
//        }
    }];

//    if (self.typeTrade == YZM_TRADE_TYPE_FOR_A_STOCK_YLB) {
//        return view;
//    }
    UILabel *label4 = [YZMAppStyle labelWithSmallWhite];
//    label4.text = @"%,今日还可点买";
    label4.text = @"%";
    [view addSubview:label4];
    [label4 mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.equalTo(self.stockUseLB.mas_right);
        make.centerY.equalTo(label1);
        make.right.equalTo(view).offset(-15);
    }];
    
//    self.stockTimeLB = [YZMAppStyle labelWithSmallYellow];
//    self.stockTimeLB.text = @"--";
//    [view addSubview:self.stockTimeLB];
//    [self.stockTimeLB mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.left.equalTo(label4.mas_right);
//        make.centerY.equalTo(label1);
//    }];
//
//    UILabel *label3 = [YZMAppStyle labelWithSmallWhite];
//    label3.text = @"次。";
//    [view addSubview:label3];
//    [label3 mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.left.equalTo(self.stockTimeLB.mas_right);
//        make.right.equalTo(view);
//        make.centerY.equalTo(label1);
//    }];
    
    return view;
}
//今日可点卖次数
- (UIView *)couldbuyTimes {
    
    UIView *view = [UIView new];
    
    UILabel *label4 = [YZMAppStyle labelWithSmallWhite];
    label4.text = @"今日还可点买";
    [view addSubview:label4];
    [label4 mas_makeConstraints:^(MASConstraintMaker *make) {
        
//        make.left.equalTo(self.stockUseLB.mas_right);
        make.left.top.bottom.equalTo(view);
    }];
    
    self.stockTimeLB = [YZMAppStyle labelWithSmallYellow];
    self.stockTimeLB.text = @"--";
    [view addSubview:self.stockTimeLB];
    [self.stockTimeLB mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(label4.mas_right);
        make.centerY.equalTo(label4);
    }];
    
    UILabel *label3 = [YZMAppStyle labelWithSmallWhite];
    label3.text = @"次";
    [view addSubview:label3];
    [label3 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.stockTimeLB.mas_right);
        make.right.equalTo(view);
        make.centerY.equalTo(label4);
    }];
    
    return view;
}

- (YZMWarningHotView *)hotView{
    if (!_hotView) {
        _hotView = [[NSBundle mainBundle] loadNibNamed:NSStringFromClass([YZMWarningHotView class]) owner:self options:nil][0];
    }
    return _hotView;
}

- (YZMCaluateView *)caluateView{
    if (!_caluateView) {
        _caluateView = [[NSBundle mainBundle] loadNibNamed:NSStringFromClass([YZMCaluateView class]) owner:self options:nil][0];
    }
    return _caluateView;
}

- (void)selectedExpense:(UIButton *)send {
    
    self.expenseBtn.selected = !self.expenseBtn.isSelected;
    if (self.expenseBtn.selected) {
        [self refreshExpenseLB];
    }else{
         self.labelTotal.text = @([self.principal doubleValue] + [self.serviceCharge doubleValue]).decimalr02fString;
    }
}

#pragma mark - Lazy

- (NSMutableArray *)arrPrincipal{
    if (!_arrPrincipal) {
        _arrPrincipal = [NSMutableArray array];
    }
    return _arrPrincipal;
}

#pragma mark - controller manager support

- (void)updateWithParams: (NSDictionary *)params
{
    self.stock = params[@"stockReal"];
    self.typeTrade= [params[@"tradeType"] intValue];
    self.stockFetchDate = [NSDate date];
}

+ (instancetype)createWithParams: (NSDictionary *)params
{
    YZMStockBuyViewController *ctrl = [[self alloc] init];
    [ctrl updateWithParams: params];
    return ctrl;
}

@end
